//
// Created by 吴喆 on 2020/4/8.
//

#include "SMLabel.h"
#include "Scene.h"
#include "../game/SpriteRender.h"
#include "TextRenderer.h"

FontAtlas *SMLabel::fontAtlas = new FontAtlas(new FTFont("../fonts/simhei.ttf")); /*NOLINT*/

SMLabel::SMLabel(Scene *scene, glm::vec2 position, float scale, std::wstring &content) : GameObject(scene), content(content) {
    GameObject::currPosition = GameObject::initPosition = position;
    init();
}

SMLabel::SMLabel(Scene *scene, glm::vec2 position, float scale, std::wstring &&content) : GameObject(scene), content(content) {
    GameObject::currPosition = GameObject::initPosition = position;
    init();
}



SMLabel::~SMLabel() {
    delete fontAtlas;
}

void SMLabel::setFontAtlas(FontAtlas *fontAtlas) {
    SMLabel::fontAtlas = fontAtlas;
}

void SMLabel::init() {
    initGameObject();
}

void SMLabel::initGameObject() {
    GameObject::initGameObject();
}

void SMLabel::setContent(const std::wstring &content) {
    SMLabel::content = content;
}

void SMLabel::update() {
    std::for_each(content.begin(), content.end(), [&](wchar_t ch) {
        chs.insert(std::pair(ch, fontAtlas->find(ch)));
    });
}

void SMLabel::render() {
    // 遍历文本中所有的字符
    auto *textRenderer = dynamic_cast<TextRenderer *>(renderer);
    assert(textRenderer != nullptr);
    std::wstring::const_iterator c;
    float x = GameObject::currPosition.x;
    for (c = content.begin(); c != content.end(); c++) {
        Character *ch = chs[*c];

        GLfloat w = ch->size.x * GameObject::size.x;
        GLfloat h = ch->size.y * GameObject::size.y;

        renderer->DrawSprite(this->scene->getCamera(), &ch->textureID, glm::vec2(GameObject::currPosition.x + x + ch->bearing.x * GameObject::size.x, GameObject::currPosition.y - (ch->size.y - ch->bearing.y) * GameObject::size.y) / 100, glm::vec2(w, h) / 100);

        // 更新位置到下一个字形的原点，注意单位是1/64像素
        x += (ch->advance >> 6) * GameObject::size.x; // 位偏移6个单位来获取单位为像素的值 (2^6 = 64)

    }
}

void SMLabel::initRenderer() {
    renderer = new TextRenderer(ResourceManager::getShader("text"));
}

